package common;


import java.io.*;
import java.net.*;
import java.rmi.RemoteException;
import java.util.ArrayList;
import client.AspettaRisp;
import client.Client;
import eccezioni.MyException;


public class ServerSocket implements ServerInterface,Serializable{
	
	private boolean okConnection;
	private BufferedReader bufferedReader;
	private BufferedReader lineReader;
	private BufferedWriter bufferedWriter;
	private Client c;
	private int k,l,m,n,o,p,r,a,b,d,e, er,f, h,gg,ggg;
	private float g;
	private char[] mex;
	private String s,tok,t, u,v,x,y,w,z,za;
	private AspettaRisp asp;
	private Socket socket;
	
	
	public static final String INDIRIZZO_IP_SERVER = /*"5.180.99.29""192.168.0.3" "5.179.220.158" "5.185.234.8"*/"localhost";
	public static final int PORTA_ASCOLTO_SERVER = 5000;
	
	
	public ServerSocket(Client client) throws IOException {
		
		c=client;
		
		try {
			socket = new Socket(INDIRIZZO_IP_SERVER, PORTA_ASCOLTO_SERVER);
		} catch (UnknownHostException e) {
			c.display("Il Server ha chiuso la connessione");
			System.exit(0);
		} 
		bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		bufferedWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		lineReader=new BufferedReader(new InputStreamReader(System.in));
		asp=new AspettaRisp(c,bufferedReader);
		asp.start();	
	}
	

	@SuppressWarnings("deprecation")
	public void closeg(String user) throws IOException{
		s=new String("@chiudiSocket,");
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		asp.setChiudiprog(true);
		asp.stop();
		bufferedReader.close();
	   	bufferedWriter.close();
	   	socket.close();
	}

	@Override
	public String creaPlayer(String user, String pass) throws IOException{
		
		s=new String("@creaUtente,user="+user+",pass="+pass);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		t=c.getRisposta();
		
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o')
			c.getVisualization().displayOk(t);
		else
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public String  login(String user, String pass)  throws IOException {
		
		s=new String("@login,user="+user+",pass="+pass);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		t=c.getRisposta();
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o'){
			for(l=k+1;mex[l]!=',';l++);
			for(m=l+1;m<mex.length;m++);
			tok=t.substring(l+1,m);
			c.getVisualization().displayOk(t.substring(0, l));
			c.setToken(Integer.parseInt(tok));
		}
		else
			c.getVisualization().displayError(t);
		return t;	
	}

	
	@Override
	public String  creaRazza(String nome, int token, char tipo) throws IOException {
		s=new String("@creaRazza,token="+token+",nome="+nome+",tipo="+tipo);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		t=c.getRisposta();
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o')
			c.getVisualization().displayOk(t);
		else
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public String  entraInPartita(int token)  throws IOException{
		s=new String("@accessoPartita,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		t=c.getRisposta();
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o')
			c.getVisualization().displayOk(t);
		else
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public String  esciDallaPartita(int token)  throws IOException{
		s=new String("@uscitaPartita,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		t=c.getRisposta();
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o')
			c.getVisualization().displayOk(t);
		else
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public ArrayList<Player> listaGiocatori(int token)  throws IOException{
		s=new String("@listaGiocatori,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		t=c.getRisposta();
		ArrayList<Player> gioc=new ArrayList<Player>();
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='l'){
			if(t.substring(k+1).length()==15)
				c.getVisualization().displayListaGiocatori(gioc);
			else{
				for(m=0;(mex[m]!=',')&&(m<mex.length-1);m++);
				for(k=m;(k<mex.length);k++){
					if(k>=(mex.length-1))
						break;	
					for(n=m+1;(mex[n]!=',')&&(n<mex.length);n++);
					gioc.add(new Player((t.substring(m+1,n))," "));
					k=n;
					m=n;
				}				
				c.getVisualization().displayListaGiocatori(gioc);
			}
		}
		else
			c.getVisualization().displayError(t);
		return null;
	}


	@Override
	public ArrayList<Player> classifica(int token)  throws IOException{
		
		int er=0;
		s=new String("@classifica,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		t=c.getRisposta();
		ArrayList<Player> classifica=new ArrayList<Player>();		
		mex = t.toCharArray();
		
		//System.out.println(t);
		
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='c'){
			if(t.substring(k+1).length()==10)
				c.getVisualization().displayClassifica(classifica);
			else{
				
				for(k=0;(k<mex.length);k++){
					if(k>=(mex.length-1))
						break;
					classifica.add(new Player(" "," "));
					for(m=k;mex[m]!='{';m++);		
					for(n=m+1;mex[n]!=',';n++);
					classifica.get(er).setNomeutente(t.substring(m+1,n));
					for(o=n+1;mex[o]!=',';o++);
					classifica.get(er).setNomespecie(t.substring(n+1,o));
					for(p=o+1;mex[p]!=',';p++);
					classifica.get(er).setPunteggio(Integer.parseInt(t.substring(o+1,p)));
					classifica.get(er).setEstchar(mex[p+1]);
					k=p+3;
					er=er+1;
				}
				c.getVisualization().displayClassifica(classifica);
			}
		}
		else
			c.getVisualization().displayError(t);
		return null;
	}


	@Override
	public String logout(int token)  throws IOException{
		s=new String("@logout,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta(); 
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o')
			c.getVisualization().displayOk(t);
		else
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public char[][] mappaGenerale(int token)  throws IOException{
		
		s=new String("@mappaGenerale,token="+token);
		int i=0,j=0;
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta(); 
	
		char[][]mappa = new char[40][40];
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='m')
		{
			for(k=0;mex[k]!='[';k++);
			for(i=0;i<40;i++)
				for(j=0;j<40;j++){
					if(k>mex.length)
						break;
					mappa[i][j]= mex[k+1];
					k=k+3;
					if(j==39){
						k=k+1;
					}
				}
			c.getVisualization().displayMappa(mappa);
		}
		else
			c.getVisualization().displayError(t);
		return null;
	}


	@Override
	public ArrayList<Dinosauro> listaDinosauri(int token)  throws IOException{
		s=new String("@listaDinosauri,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta();
		ArrayList<Dinosauro> dinos=new ArrayList<Dinosauro>(); 
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		
		if(mex[k+1]=='l'){
			if(t.substring(k+1).length()==14||t.substring(k+1).length()==15)
				c.getVisualization().displayListaDinosauri(dinos);
			else{
				for(p=k+1;mex[p]!=',';p++);
				for(k=p+1;(k<mex.length);k++){
					if(k>=(mex.length-1))
						break;
					for(m=k;(mex[m]!='(')&&(m<mex.length-1);m++);		
					for(n=m+1;(mex[n]!=')')&&(n<mex.length-1);n++);
					//System.out.println(Integer.parseInt(t.substring(m+1,n)));
					dinos.add(new Carnivoro(" ",Integer.parseInt(t.substring(m+1,n)),0,0," "));
					k=n+1;
				}				
				c.getVisualization().displayListaDinosauri(dinos);
			}
		}
		else
			c.getVisualization().displayError(t);
		return null;
	}


	
	public Casella[][] vistaLocale(int token, int idDino)  throws IOException{
		
		s=new String("@vistaLocale,token="+token+",idDino="+idDino);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta();
		Casella[][] vista; 
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='v')
		{
			for(l=k+1;mex[l]!='{';l++);
			for(m=l+1;mex[m]!=',';m++);
			e=Integer.parseInt(t.substring(l+1,m));
			for(n=m+1;mex[n]!='}';n++);
			f=Integer.parseInt(t.substring(m+1,n));
			for(o=n+1;mex[o]!='{';o++);
			for(r=o+1;mex[r]!=',';r++);
			d=Integer.parseInt(t.substring(o+1,r));
			
			vista=new Casella[d][d];
			
			for(k=0;mex[k]!='[';k++); 
			for (int i=0;i<d;i++)
				for (int j=0;j<d;j++){ 
					String s2=new String("");
					switch(mex[k+1]){
					
						case('*'):
							if((i==d-1)&&(j==0))
								vista[i][j]=new Terra(e,f);
							else	
								vista[i][j]=null;
							k++;
							break;
						
						case('t'):
							if((i==d-1)&&(j==0))
								vista[i][j]=new Terra(e,f);
							else
								vista[i][j]=new Terra(0,0);
							k++;
							break;
						
						case('a'):
							if((i==d-1)&&(j==0))
								vista[i][j]=new Acqua(e,f);
							else
								vista[i][j]=new Acqua(0,0);
							k++;
							break;
						
						case('v'):
							if((i==d-1)&&(j==0))
								vista[i][j]=new Vegetazione(e,f);
							else	
								vista[i][j]=new Vegetazione(0,0);
							for(gg=k+1;mex[gg]!=',';gg++);
							for(ggg=gg;mex[ggg]!=']';ggg++);
							s2=t.substring(gg+1,ggg);
							//System.out.println(s2);
							vista[i][j].setEnergia(Integer.parseInt(s2));				
							k++;
							break;
							
						case('c'):
							if((i==d-1)&&(j==0))
								vista[i][j]=new Carogna(e,f);
							else	
								vista[i][j]=new Carogna(0,0);
							for(gg=k+1;mex[gg]!=',';gg++);
							for(ggg=gg;mex[ggg]!=']';ggg++);
							s2=t.substring(gg+1,ggg);
							//System.out.println(s2);
							vista[i][j].setEnergia(Integer.parseInt(s2));
							k++;
							break;
						
						case('d'):
							if((i==d-1)&&(j==0))
								vista[i][j]=new Terra(e,f);
							else
								vista[i][j]=new Terra(0,0);
							h=3;
							System.out.println(s2);
							for(gg=k+1;mex[gg]!=',';gg++);
							for(ggg=gg;mex[ggg]!=']';ggg++);
							s2=t.substring(gg+1,ggg);
							//System.out.println(s2);
							Dinosauro dinoz=new Erbivoro("ciao",Integer.parseInt(s2),0,0,"babbo");
							vista[i][j].setOccupa(dinoz);
							k++;
							break;
					}
					
					if((i==d-1)&&(j==d-1))
						break;
					for(gg=k+1;mex[gg]!='[';gg++)
						k=k+1;
					k=k+1;
				}
 
			c.getVisualization().displayVistaLocale(vista[vista.length-1][0].getPosizioneI(), vista[vista.length-1][0].getPosizioneJ(), vista.length, vista.length, vista);
		}
		else
			c.getVisualization().displayError(t);
		return null;
	}


	@Override
	public Dinosauro statoDinosauro(int token, int idDino)  throws IOException{
		
		s=new String("@statoDinosauro,token="+token+",idDino="+idDino);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush();
		t=c.getRisposta();
		
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='s')
		{ 
			for(l=k+1;mex[l]!=',';l++);
			for(m=l+1;mex[m]!=',';m++);
			u=t.substring(l+1,m);
			//u proprietario
			
			for(n=m+1;mex[n]!=',';n++);
			v=t.substring(m+1,n);
			//v razza
			
			char nutri=mex[n+1];
			
			for(o=n+3;mex[o]!='{';o++);
			for(r=o+1;mex[r]!=',';r++);
			w=t.substring(o+1,r);
			a=Integer.parseInt(w);
			//pos i  
			for(b=r+1;mex[b]!='}';b++);
			z=t.substring(r+1,b);
			d=Integer.parseInt(z);
			//pos j
			
			for(e=b+2;(mex[e]!=',');e++);
			za=t.substring(b+2,e);
			er=Integer.parseInt(za); 
			//dimensione
			

			for(f=e+2;mex[f]!=',';f++)
			x=(t.substring(e+1,f));
			if(x.equals("N/")){
				g=-1;
				f=-1;
			}
			else{
				g=Float.parseFloat(x);
				for(h=f+2;h<mex.length;h++);
				y=t.substring(f+1,h);
				f=Integer.parseInt(y);
			}
					
			Dinosauro dino;
			if(nutri=='e')
				dino = new Erbivoro(u, 0, a, d, v);
			else
				dino = new Carnivoro(u, 0, a, d, v);
			
			dino.setD(er);
			dino.setEnergia(g);
			dino.setEta(f);
		
			c.getVisualization().displayStatoDinosauro(dino);
		}
		else
			c.getVisualization().displayError(t);
		return null;
	}


	@Override
	public String muoviDinosauro(int token, int idDino, int desti, int destj)  throws IOException{
		s=new String("@muoviDinosauro,token="+token+",idDino="+idDino+",dest={"+desti+","+destj+"}");
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta();
		
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o')
			c.getVisualization().displayOk(t);
		else
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public String cresciDinosauro(int token, int idDino)  throws IOException{
		s=new String("@cresciDinosauro,token="+token+",idDino="+idDino);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta();
		
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o')
			c.getVisualization().displayOk(t);
		else
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public String deponiUovo(int token, int idDino)  throws IOException{
		s=new String("@deponiUovo,token="+token+",idDino="+idDino);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta();
		
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(mex[k+1]=='o')
			c.getVisualization().displayOk(t);
		else
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public String confermaTurno(int token)  throws IOException{
		s=new String("@confermaTurno,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta();
		
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(!(mex[k+1]=='o')) 
			c.getVisualization().displayError(t);
		return t;
	}


	@Override
	public String passaTurno(int token)  throws IOException{
		
		s=new String("@passaTurno,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta();
		
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		if(!(mex[k+1]=='o')) 
			c.getVisualization().displayError(t);
		return t;
	}


	public boolean isOkConnection() {
		return okConnection;
	}

	
	public void setOkConnection(boolean okConnection) {
		this.okConnection = okConnection;
	}


	public BufferedReader getBufferedReader() {
		return bufferedReader;
	}


	public void setBufferedReader(BufferedReader bufferedReader) {
		this.bufferedReader = bufferedReader;
	}


	public BufferedWriter getBufferedWriter() {
		return bufferedWriter;
	}


	public void setBufferedWriter(BufferedWriter bufferedWriter) {
		this.bufferedWriter = bufferedWriter;
	}



	@Override
	public String login(String user, String pass, ClientInterface clint) throws IOException, RemoteException {
		return "";
	}


	@Override
	public ArrayList<Dinosauro> listaDinosauriGlobal(int token) throws IOException, RemoteException, MyException {
		s=new String("@listaDinosauriGlobal,token="+token);
		bufferedWriter.write(s);
		bufferedWriter.newLine();
		bufferedWriter.flush(); 
		t=c.getRisposta();
		ArrayList<Dinosauro> dinos=new ArrayList<Dinosauro>();
		
		mex = t.toCharArray();
		for(k=0;mex[k]!='@';k++);
		
		if(mex[k+1]=='l'){
			if(t.substring(k+1).length()==20||t.substring(k+1).length()==21)
				c.getVisualization().displayListaDinosauriGlobal(dinos,c.getUsr());
			else{
				for(p=k+1;mex[p]!=',';p++);
				for(k=p+1;(k<mex.length);k++){
					if(k>=(mex.length-1))
						break;
					for(m=k;(mex[m]!='(')&&(m<mex.length-1);m++);		
					for(n=m+1;(mex[n]!=',')&&(n<mex.length-1);n++);
					for(o=n+1;(mex[o]!=')')&&(o<mex.length-1);o++); 
					dinos.add(new Carnivoro(t.substring(n+1,o),Integer.parseInt(t.substring(m+1,n)),0,0,"ciao"));
					k=o+1;
				}				
				c.getVisualization().displayListaDinosauriGlobal(dinos,c.getUsr());
			}
		}
		else
			c.getVisualization().displayError(t);
		return null;
	}


}